# coding=utf8
import time
import os
import aiohttp
import json
import pandas as pd
from asyncio import get_event_loop
from coordinatransfer import bd09_to_gcj02
import numpy as np
import requests

# with open('/home/mm/Downloads/homestay.txt', 'r') as rf:
#     tasks = rf.read()
tujia = pd.read_pickle('/home/mm/Documents/bnb_data_wrangler/tujia_details.pkl')
airbnb = pd.read_pickle('/home/mm/Documents/bnb_data_wrangler/airbnb_details.pkl')
muniao = pd.read_pickle('/home/mm/Documents/bnb_data_wrangler/muniao_details.pkl')
xiaozhu = pd.read_pickle('/home/mm/Documents/bnb_data_wrangler/pig2_details.pkl')
mayi = pd.read_pickle('/home/mm/Documents/bnb_data_wrangler/muniao_details.pkl')

# with open("/home/mm/Documents/bnb_data_wrangler/task_coord.csv", 'a') as wf:
#     for line in tasks.split("\n"):
#         if "airbnb" in line.split("_")[0]:
#             a, b = np.ndenumerate(airbnb[['longitude', 'latitude']].loc[airbnb['id'] == line.split("_")[1]])
#             wf.write(line + "," + a[1] + "," + b[1] + "\n")
#         elif "muniao" in line.split("_")[0]:
#             res = muniao[['longitude', 'latitude']].loc[muniao['id2'] == line.split("_")[1]]
#             a, b = np.ndenumerate(res)
#             coord = bd09_to_gcj02(a[1], b[1])
#             wf.write(line + "," + str(coord[1]) + "," + str(coord[0]) + "\n")
#         elif "tujia" in line.split("_")[0]:
#             a, b = np.ndenumerate(tujia[['longitude', 'latitude']].loc[tujia['id2'] == line.split("_")[1]])
#             coord = bd09_to_gcj02(a[1], b[1])
#             wf.write(line + "," + str(coord[1]) + "," + str(coord[0]) + "\n")
appkey = "fc254b20e2ebec432cb90276a0af37ea"
# longitude = "113.25292205793951"
# latitude = "23.125836383880394"
# location = longitude + "," + latitude
# url = "https://restapi.amap.com/v3/geocode/regeo?output=json&extensions=all&key={}&location={}".format(appkey, location)
#
# r = requests.get(url)
# print(r.text)
# 将所有经纬度读出来使用异步 调取api接口转换成 一个大词典
if os._exists('/home/mm/Documents/bnb_data_wrangler/coord_towncode.csv'):
    df_csv = pd.read_csv('/home/mm/Documents/bnb_data_wrangler/coord_towncode.csv', sep=",")
    len_csv = len(df_csv.index)
else:
    len_csv = 0

with open('/home/mm/Documents/bnb_data_wrangler/coord_towncode.csv', 'a') as af:

    for i in tujia[['longitude', 'latitude']].values[len_csv:]:
        a, b = i
        coord = bd09_to_gcj02([a, b])
        longitude = coord[0]
        latitude = coord[1]
        location = str(longitude) + "," + str(latitude)
        url = "https://restapi.amap.com/v3/geocode/regeo?output=json&extensions=all&key=fc254b20e2ebec432cb90276a0af37ea&location={}".format(location)
        r = requests.get(url)
        json_res = json.loads(r.text)
        towncode = json_res["regeocode"]["addressComponent"]["towncode"]
        try:
            assert type(towncode) is str
        except Exception as e:
            print(str(a) + "," + str(b))
            continue
        af.write(str(a) + "," + str(b) + "," + towncode + "\n")
